package de.slothsoft.wasbinich.android.util;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.PictureDrawable;
import android.os.Build;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.caverock.androidsvg.SVG;
import com.caverock.androidsvg.SVGParseException;

import de.slothsoft.wasbinich.android.R;

public final class SvgUtil {

    public static void setSvgToButton(Context context, Button button, int id) {
	setSvgToView(context, button, id, R.dimen.button_width, R.dimen.button_height);
    }

    public static void setSvgToChronometer(Context context, View view, int id) {
	setSvgToView(context, view, id, R.dimen.chronometer_width, R.dimen.chronometer_height);
    }

    public static void setSvgToView(Context context, View view, int id, int widthId, int heightId) {
	try {
	    int width = context.getResources().getDimensionPixelSize(widthId);
	    int height = context.getResources().getDimensionPixelSize(heightId);
	    setLayerTypeToSoftware(view);
	    SVG svg = SVG.getFromResource(context, id);
	    view.setBackgroundDrawable(new PictureDrawable(svg.renderToPicture(width, height)));
	} catch (SVGParseException e) {
	    throw new RuntimeException(e);
	}
    }

    public static void setSvgToBackground(Context context, View view, int id) {
	BitmapDrawable drawable = (BitmapDrawable) context.getResources().getDrawable(R.drawable.background);
	drawable.setTileModeX(TileMode.REPEAT);
	view.setBackgroundDrawable(drawable);
    }

    public static void setSvgToImageView(Context context, ImageView imageView, int id) {
	setLayerTypeToSoftware(imageView);
	imageView.setImageDrawable(getSvg(context, id));
    }

    public static Drawable getSvg(Context context, int id) {
	try {
	    SVG svg = SVG.getFromResource(context, id);
	    return new PictureDrawable(svg.renderToPicture());
	} catch (Exception e) {
	    throw new RuntimeException(e);
	}
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private static void setLayerTypeToSoftware(View view) {
	if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
	    view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
	}
    }

    private SvgUtil() {
	// hide me
    }

}
